<?php

namespace app\admin\controller;

use app\common\controller\Admin;
use app\ads\controller\Api;
use think\Validate;

/**
 * 书库
 *
 * @Author 小邓
 * @DateTime 2022-11-05
 */
class Gzh extends Admin
{

    public function _initialize()
    {
        parent::_initialize();

    }


    public function _empty()
    {

        $action = ACTION_NAME;
        $keyword = input('get.keyword') ?? null;
        $map = [];
        $pageSize = 50;
        $list = db('gzh_official_account');
        if ($keyword) {
            $map['name|account'] = ["like", "%$keyword%"];
            $list->where($map);
        }

        // 男女频道筛选
        if (input('get.channel') && input('get.channel') != 999999) {
            $list->where('channel', input('get.channel'));
        }
        // 录入人筛选
        if (input('get.uid') && input('get.uid') != 999999) {
            $list->where('uid', input('get.uid'));
        }
        // 运营专员筛选
        if (input('get.operate') && input('get.operate') != 999999) {
            $list->where('operate', input('get.operate'));
        }

        switch (input('get.pub_sort')) {
            case 2:
                $order = 'auth_date desc';
                break;
            case 3:
                $order = 'auth_date asc';
                break;
            case 4:
                $order = 'fans_num desc';
                break;
            case 5:
                $order = 'fans_num asc';
                break;
            default:
                $order = 'id desc';

        }

        $list = $list->order($order)->paginate($pageSize, false, ['type' => 'page\Page', 'query' => request()->param()]);
        foreach ($list as $k => $v) {
            $list[$k] = $v;
        }
        $page = $list->render();

        $userlist = db('member')->column("uid,username");
        $jumpurl = url() . "?" . http_build_query(request()->param());
        $this->assign(compact('keyword', 'list', 'page', 'userlist', 'jumpurl'));
        $this->setMeta("账号管理");
        return view('gzh/' . $action);
    }

    /**
     * Notes: 新增
     * User: zhu
     * Date: 2022/11/24
     * Time: 10:38
     * @return null
     */
    public function add()
    {
        if (IS_POST) {
            $post = input('post.');
            $post['uid'] = session('user_auth.uid');
            $post['auth_date'] = date('Y-m-d', time());
            $post['create_time'] = time();
            db('gzh_official_account')->insert($post);
            return $this->success("成功！");
        }
        return $this->error("失败！");
    }


    /**
     * Notes:修改公众号信息
     * User: zhu
     * Date: 2022/11/24
     * Time: 10:37
     * @return null
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function edit()
    {
        if (IS_POST) {
            $post = input('post.');
            if ($post['id']) {
                $post["update_time"] = time();
                db('gzh_official_account')->where("id=" . $post['id'])->update($post);
                return $this->success("修改成功！");
            } else {
                $insertData = [
                    'name' => $post['name'],
                    'account' => $post['account'],
                    'email' => $post['email'],
                    'password' => $post['password'],
                    'email_password' => $post['email_password'],
                    'originalId' => $post['originalId'],
                    'appid' => $post['appid'],
                    'channel' => $post['channel'],
                    'style' => $post['style'],
                    'fans_num' => $post['fans_num'],
                    'subject' => $post['subject'],
                    'binding' => $post['binding'],
                    'admin' => $post['admin'],
                    'operate' => $post['operate'],
                    'create_time' => time(),
                    'update_time' => time()
                ];
                db('gzh_official_account')->insert($insertData);
                return $this->success("添加成功");
            }
        }
        return $this->error("失败！");
    }

    /**
     * Notes: 公众号推文标题页
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author: Zhu
     * @since: 2023/1/9 16:09
     */
    public function twtitle()
    {
        $action = ACTION_NAME;
        $params = request()->param();
        $uid   = session('user_auth.uid');
        // 用户列表
        $userlist  = db('member');
        if(!in_array($uid, [1,52,53])){
            $userlist = $userlist->where('pid', $uid)->where('uid', '<>', $uid);
        }
        $userlist = $userlist->column("uid,username");
        // 等级
        $level = isset($params['level']) ? $params['level'] : 99;
        // 频道
        $channel = isset($params['channel']) ? $params['channel'] : 99;
        // 用户搜素
        $userid = isset($params['userid']) ? $params['userid'] : 99999;
        // 日期
        $startDate = isset($params['startdata']) ? $params['startdata'] : date('Y-m-d', time());
        $endDate = isset($params['enddata']) ? $params['enddata'] : date('Y-m-d', time());
        $this->assign(compact('userlist','userid', 'startDate', 'endDate'));
        //分类
        $categoryList = db('ads_material_category')->column("id,title");
        $category_id = isset($params['category_id']) ? $params['category_id'] : 99999;
        $this->assign(compact('level', 'channel','categoryList','category_id'));
        // 书籍列表
        $bookList = db('ads_material_book')->order('name desc,sort desc,id asc')->column('id,title');
        $book_id = isset($params['book_id']) ? $params['book_id'] : 9999999;
        $this->assign(compact('bookList', 'book_id'));
        // 标签
        $tags = db('ads_material_tag')->column('id,title');
        $tagId = isset($params['tag_id']) ? $params['tag_id'] : 99999;
        $this->assign(compact('tags', 'tagId'));

        //获取列表数据
        $list = db('gzh_twtitle')
            ->whereBetween('create_time', [strtotime(date('Y-m-d 00:00:00', strtotime($startDate))), strtotime(date('Y-m-d 23:59:59', strtotime($endDate)))]);
        if(!in_array($uid, [1,52,53])){
            $list = $list->where("uid = $uid");
        }
        if (isset($params['keyword']) &&  !empty($params['keyword'])) {
            $keyword = $params['keyword'];
            $list = $list->where("content like '%$keyword%'");
        }
        if (isset($params['category_id']) && $params['category_id'] != 99999) {
            $list = $list->where("category_id = " . $params['category_id']);
        }
        if (isset($params['channel']) && $params['channel'] != 99) {
            $list = $list->where("channel = " . $params['channel']);
        }

        if (isset($params['tag_id']) && $params['tag_id'] != 99999) {
            $tag = $params['tag_id'];
            $list = $list->where("FIND_IN_SET($tag, tag)");
        }
        if (isset($params['book_id']) && $params['book_id'] != 9999999) {
            $list = $list->where("book_id = " . $params['book_id']);
        }
        if (isset($params['level']) && $params['level'] != 99) {
            $list = $list->where("level = " . $params['level']);
        }
        if ($userid <> 99999) {
            $list = $list->where("uid", $userid);
        }

        $list = $list->order('create_time', 'desc')->paginate( 50, false, [ 'type'=> 'page\Page' ,'query' => request()->param()] );
        foreach ($list as $k => $v) {
            if (isset($userlist[$v['uid']])) {
                $v['uname'] = $userlist[$v['uid']];
            } else {
                $v['uname'] = '';
            }
            if (isset($bookList[$v['book_id']])) {
                $v['book_name'] = $bookList[$v['book_id']];
            } else {
                $v['book_name'] = '';
            }
            $v['tag'] = explode(',', $v['tag']);
            $ta = [];
            foreach ($v['tag'] as $kk => $vv) {
                if (isset($tags[$vv])) {
                    $ta[] = $tags[$vv];
                }
            }
            $v['tags'] = $ta;
            $list[$k] = $v;
        }
        $page = $list->render();
        $this->assign(compact('list', 'page'));
        $this->setMeta("推文标题");
        return view('gzh/' . $action);
    }

    /**
     * Notes: 新增公众号推文标题
     * @return null
     * @since: 2023/1/9 16:09
     * @author: Zhu
     */
    public function addTwtitle()
    {
        $params = request()->param();
        $validate = new Validate([
            'level'  => 'number',
            'channel' => 'number',
            'category_id' => 'number',
            'book_id' => 'number',
            'click_volume' => 'float',
            'click_rate' => 'float',
            'return_money' => 'float',
            'score' => 'number'
        ],[
            'level.number' => '级别信息错误',
            'channel.number' => '频道信息错误',
            'category_id.number' => '分类信息错误',
            'book_id.number' => '书籍信息错误',
            'click_volume.float' => '点击量必须是数值',
            'click_rate.float' => '点击率必须是数值',
            'return_money.float' => '回款必须是数值',
            'score.score' => '评分必须是数值'
        ]);
        if (!$validate->check($params)) {
            return $this->error($validate->getError());
        }
        if (empty($params['ebook']) && empty($params['content'])) {
            return $this->error('请输入标题内容或上传文件');
        }
        $uid = session('user_auth.uid');
        $params['create_time'] = time();
        $params['uid'] = $uid;

        if (isset($params['tag']) && is_array($params['tag']) && !empty($params['tag'])) {
            $params['tag'] = implode(',',$params['tag']);
        }
        unset($params['id']);
        foreach ($params as $k => $v) {
            $params[$k] = trim($v);
        }
        $data = [];
        if (!empty($params['ebook'])) {
            $line = [];
            $file = fopen($params['ebook'],"r");
            if ($file) {
                // 生成目录信息
                while (!feof($file)) {
                    $line[] = trim(fgets($file));
                }
            }
            if (!empty($line)) {
                foreach ($line as $v) {
                    $data[] = array_merge($params, ['content' => $v]);
                }
            }
        }
        if (!empty($params['content'])) {
            $data = array_merge($data, [$params]);
        }
        $addTwtitle = db('gzh_twtitle')->insertAll($data);
        if ($addTwtitle) {
            return $this->success("成功！");
        }
        return $this->error("失败！");
    }

    /**
     * Notes: 修改推文标题
     * @return null
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @since: 2023/1/10 10:09
     * @author: Zhu
     */
    public function editTwtitle()
    {
        $params = request()->param();
        if (!isset($params['id'])) {
            return $this->success("缺少id！");
        }
        $params["update_time"] = time();

        $params['tag'] = is_array($params['tag']) ? implode(',',$params['tag']) : $params['tag'];
        $edit = db('gzh_twtitle')->where('id', $params['id'])->update($params);
        if ($edit) {
            return $this->success("修改成功！");
        }
        return $this->error('修改失败');
    }

    /**
     * Notes:删除
     * @return null
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @since: 2023/1/9 16:11
     * @author: Zhu
     */
    public function del() {
        $id = $this->getArrayParam('id');
        $type = request()->param('type');
        if (empty($id) || empty($type)) {
            return $this->error("非法操作！");
        }
        switch ($type) {
            // 公众号列表
            case 'list':
                $del = db('gzh_official_account')->whereIn('id', $id)->delete();
                break;
            // 推文标题
            case 'twtitle':
                $del = db('gzh_twtitle')->whereIn('id', $id)->delete();
                break;
            // 消息模板
            case 'template':
                $del = db('gzh_msg_template')->whereIn('id', $id)->delete();
                break;
            case 'bbkz':
                $del = db('gzh_version')->whereIn('id', $id)->delete();
        }
        if ($del) {
            return $this->success("删除成功！");
        }
        return $this->error("删除失败！");
    }

    /**
     * Notes: 消息模板
     * @return \think\response\View
     * @throws \think\exception\DbException
     * @author: Zhu
     * @since: 2023/1/10 10:02
     */
    public function msgmb()
    {
        $action = ACTION_NAME;
        $params = request()->param();
        $uid   = session('user_auth.uid');
        // 书籍列表
        $bookList = db('ads_material_book')->order('name desc,sort desc,id asc')->column('id,title');
        $list = db('gzh_msg_template');
        if(!in_array($uid, [1,52,53])){
            $list = $list->where("uid = $uid");
        }
        $type = 0;
        if (isset($params['type'])) {
            $list = $list->where('type', $params['type']);
            $type = $params['type'];
        }
        $list = $list->order('create_time', 'desc')->paginate( 32, false, [ 'type'=> 'page\Page' ,'query' => request()->param()] );
        $userlist  = db('member');
        if(!in_array($uid, [1,52,53])){
            $userlist = $userlist->where('pid', $uid)->where('uid', '<>', $uid);
        }
        $userlist = $userlist->column("uid,username");
        foreach ($list as $k => $v) {
            if (isset($userlist[$v['uid']])) {
                $v['uname'] = $userlist[$v['uid']];
            } else {
                $v['uname'] = '';
            }

            if (isset($bookList[$v['book_id']])) {
                $v['book_name'] = $bookList[$v['book_id']];
            } else {
                $v['book_name'] = '';
            }
            $list[$k] = $v;
        }
        $page = $list->render();
        $this->assign(compact('bookList','list', 'page', 'type'));
        $this->setMeta("推文标题");
        return view('gzh/' . $action);
    }

    /**
     * Notes: 新增消息模板
     * @return null
     * @since: 2023/1/10 10:02
     * @author: Zhu
     */
    public function addTemplate()
    {
        $params = request()->param();
        $validate = new Validate([
            'type' => 'require|integer',
            'book_id'  => 'require|integer'
        ],[
            'type.require' => '请选择类型',
            'book_id.require' => '请选择书籍'
        ]);
        if (!$validate->check($params)) {
            return $this->error($validate->getError());
        }
        if (empty($params['ebook']) && empty($params['content'])) {
            return $this->error('请填写内容或上传文件');
        }
        $uid = session('user_auth.uid');
        $params['create_time'] = time();
        $params['uid'] = $uid;
        $data = [];
        if (!empty($params['ebook'])) {
            $line = [];
            $file = fopen($params['ebook'],"r");
            if ($file) {
                // 生成目录信息
                while (!feof($file)) {
                    $line[] = trim(fgets($file));
                }
            }
            if (!empty($line)) {
                foreach ($line as $v) {
                    $data[] = array_merge($params, ['content' => $v]);
                }
            }
        }
        if (!empty($params['content'])) {
            $data = array_merge($data, [$params]);
        }
        $addTemplate = db('gzh_msg_template')->insertAll($data);
        if ($addTemplate) {
            return $this->success("删除成功！");
        }
        return $this->error("删除失败！");
    }

    /**
     * Notes: 复制
     * @return null
     * @throws \think\Exception
     * @author: Zhu
     * @since: 2023/1/10 10:25
     */
    public function copy()
    {
        $params = request()->param();
        if (!isset($params['type'])) {
            return $this->error('缺少类型');
        }
        if (!isset($params['id'])) {
            return $this->error('缺少id');
        }
        $type=$params['type'];
        switch ($type) {
            // 推文标题
            case 'twtitle':
                $copy = db('gzh_twtitle')->where('id', $params['id'])->setInc('copy');
                break;
            // 消息模板
            case 'template':
                $copy = db('gzh_msg_template')->where('id', $params['id'])->setInc('copy');
                break;
        }
        if ($copy) {
            return $this->success("复制成功！");
        }
        return $this->error("复制失败！");

    }

    /**
     * Notes:版本汇总
     * @return \think\response\View
     * @throws \think\exception\DbException
     * @author: Zhu
     * @since: 2023/1/12 15:53
     */
    public function bbkz()
    {
        $action = ACTION_NAME;
        $params = request()->param();
        $uid   = session('user_auth.uid');

        // 用户列表
        $userlist  = db('member');
        if(!in_array($uid, [1,52,53])){
            $userlist = $userlist->where('pid', $uid)->where('uid', '<>', $uid);
        }
        $userlist = $userlist->column("uid,username");
        // 用户搜素
        $userid = isset($params['userid']) ? $params['userid'] : 99999;
        // 日期
        $startDate = isset($params['startdata']) ? $params['startdata'] : date('Y-m-d', time());
        $endDate = isset($params['enddata']) ? $params['enddata'] : date('Y-m-d', time());
        $this->assign(compact('userlist','userid', 'startDate', 'endDate'));
        // 书籍列表
        $bookList = db('ads_material_book')->order('name desc,sort desc,id asc')->column('id,title');

        $list = db('gzh_version')
            ->whereBetween('create_time', [strtotime(date('Y-m-d 00:00:00', strtotime($startDate))), strtotime(date('Y-m-d 23:59:59', strtotime($endDate)))]);
        if(!in_array($uid, [1,52,53])){
            $list = $list->where("uid = $uid");
        }
        if (isset($params['keyword']) &&  !empty($params['keyword'])) {
            $keyword = $params['keyword'];
            $list = $list->where("name like '%$keyword%'");
        }
        if ($userid <> 99999) {
            $list = $list->where("uid", $userid);
        }
        $list =  $list->paginate( 32, false, [ 'type'=> 'page\Page' ,'query' => request()->param()] );
        foreach ($list as $k =>$v) {
            $v['img'] = explode(',', $v['file_path']);
            foreach ($v['img'] as $kk =>$vv) {
                $v['img'][$kk] = substr($vv,1);
            }
            $list[$k] = $v;
        }
        $page = $list->render();
        $this->assign(compact('bookList', 'list', 'page'));
        $this->setMeta("汇总");
        return view('gzh/' . $action);
    }

    /**
     * Notes: 版本汇总新增
     * @return null
     * @since: 2023/1/12 15:53
     * @author: Zhu
     */
    public function addBbkz()
    {
        $params = request()->param();
        $validate = new Validate([
            'name'  => 'require'
        ],[
            'name.require' => '请输入名称'
        ]);
        if (!$validate->check($params)) {
            return $this->error($validate->getError());
        }
        if (empty($params['file_path'])) {
            return $this->error('请上传内容');
        }
        $uid = session('user_auth.uid');
        $params['create_time'] = time();
        $params['uid'] = $uid;
        $addBbkz = db('gzh_version')->insert($params);
        if ($addBbkz) {
            return $this->success("成功！");
        }
        return $this->error("失败！");
    }

}